<?php 

class shortURL {
	protected $db;
	protected $gpc;
	protected $basex;
	
	public $oldurl;
	public $newurl;
	public $keycode;
	public $error;
	public $message;
	
	function ShortURL($min_digits = 1) {
		$this->db = ADONewConnection(DB_CONNECTION_URL);
		$this->gpc = get_magic_quotes_gpc();
		
		// create new basex decoder/encoder
		require_once('basex.class.php');
		$this->basex = new basex();
		$this->basex->min_digits = $min_digits;
		// Set the charset to use in your base
		$this->basex->charset = array_merge($this->basex->charset,$charset = range("0","9"));
		$this->basex->charset = array_merge($this->basex->charset,$charset = range("a","z"));
		//$basex->charset = array_merge($basex->charset,$charset = range("A","Z"));
		// Set the base to whatever you want, leaving it blank causes it to use the sizeof(charset)
		$this->basex->base = sizeof($this->basex->charset);
		
	}

	function generate($oldurl, $method = "unknown") {
		
		// collect data from user
		$this->oldurl = $oldurl;
		if ($this->oldurl != "") {
			$error = "";
			// add protocol if required
			if (substr_count($this->oldurl, ':') == 0) {
				$this->oldurl = "http://" . $this->oldurl;
			}
			// tack / on the end of domain names only
			if (substr_count($this->oldurl, '/') <= 2) {
				$this->oldurl .= "/"; 
			}
			// check if url is taken, if so, display existing short url
			$qurl = $this->db->qstr($this->oldurl, $this->gpc);
			$qmethod = $this->db->qstr($method, $this->gpc);
			$query = 'SELECT id FROM links WHERE url LIKE '.$qurl. ' LIMIT 1';
			$result = $this->db->Execute($query);

			if (!$result) {
				die("DB Error: ". $this->db->ErrorMsg(). " " . $query);
			} elseif ($result->RecordCount() > 0) {
				// found the link, use this keycode.
				$this->message = "Hey, someone already made this one for you!";
				while ($arr = $result->FetchRow()) {
					$id= $arr[0];
				}
				// TODO: Need to get old pretty string from DB.
				$this->keycode = $this->basex->basex_encode($id);
			} else if (strstr($this->oldurl, BASE_URL) !== false) {
				// they've pasted a generated url?
				$this->error = "Nice try, but it's not really gonna get any shorter than that!";
				$keycode = substr($this->oldurl, strpos($this->oldurl, '/', 8)+1);
				$this->keycode = $this->basex->basex_encode($this->basex->basex_decode($keycode));
			} else {
				// it wasn't in the database, lets add it.

				// make unique shortstring
				$ip = @$_SERVER['HTTP_X_FORWARDED_FOR'];
				if ($ip == '') {
					$ip = @$_SERVER['REMOTE_ADDR'];
				}
				$qip = $this->db->qstr($ip, $this->gpc);
				$query = "INSERT INTO links (url, ipaddress, method) VALUES (".$qurl.", ".$qip." ,".$qmethod." )";
				if ($this->db->Execute($query) === false) {
					die("DB Error: ". $this->db->ErrorMsg(). " " . $query);
				}
				// get insert_id and make meganum from it
				$id = $this->db->Insert_ID();
				$this->keycode = $this->basex->basex_encode($id);
				// save to database
			}
			/*
			// get the details off the net, like title and h1 and h2
			include_once('Snoopy.class.php');
			$snoopy = new Snoopy();
			$snoopy->proxy_host = PROXY_HOST;
			$snoopy->proxy_port = PROXY_PORT;
			$snoopy->proxy_user = PROXY_USER;
			$snoopy->proxy_pass = PROXY_PASS;
			if ($snoopy->fetch($url)) {
				$result = $snoopy->results;
				$title = getTagContentsFromString($result, '<title>', '</title>');
			} else {
				echo $snoopy->error;
			}
			*/
			$this->newurl = BASE_URL.$this->keycode;
			return ($this->newurl);
		} else {
			$this->error = "Umm, that's not a real URL, is it?";
			return false;
		}
	}
	
	function getURL($keycode) {
		if ($keycode == "0") {
			$url = "http://urltea.com/";
		} else {
			$id = $this->basex->basex_decode($keycode);
			$query = 'SELECT url FROM links WHERE id = '.$id. ' LIMIT 1';
			$result = $this->db->Execute($query);

			if (!$result) {
				die("DB Error: ". $this->db->ErrorMsg(). " " . $query);
			} else {
				if ($result->RecordCount() > 0) {
					while ($arr = $result->FetchRow()) {
						$this->newurl= $arr[0];
					}
					// record stat
					$query = "UPDATE links SET hits = hits + 1 WHERE id = ".$id.";";
					if ($this->db->Execute($query) === false) {
						die("DB Error: ". $this->db->ErrorMsg(). " " . $query);
					}
				} else {
					$this->error = "Hey, we couldn't find this one in the database...";
					return false;
				}
			}
		}
		$this->keycode = $keycode;
		return $this->newurl;
	}
	
	function getStats($keycode) {
		$id = $this->basex->basex_decode($keycode);
		$query = 'SELECT *, UNIX_TIMESTAMP(made) AS unix_made FROM links WHERE id = '.$id. ' LIMIT 1';
		$result = $this->db->Execute($query);

		if (!$result) {
			die("DB Error: ". $this->db->ErrorMsg(). " " . $query);
		} else {
			if ($result->RecordCount() > 0) {
				while ($arr = $result->FetchRow()) {
					$link = $arr;
				}
			} else {
				$this->error = "Hey, we couldn't find this one in the database...";
				return false;
			}
		}
		$link['keycode'] = $keycode;
		return $link;
	}
	
}

?>